package com.zc.shiro;


import com.zc.dao.UsersMapper;
import com.zc.entity.Users;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.print.DocFlavor;
import java.util.List;

/**
 * 利用注解方式实现权限控制
 */
public class MyRealm extends AuthorizingRealm {

	@Resource
	private UsersMapper userDao;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	//认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)arg0;
		String username = token.getUsername();
//		char[] password = token.getPassword();
		Users userInfo = userDao.selectByName(username);
		if(userInfo==null){
			return null;
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo,userInfo.getPassword(),this.getClass().getName());
		return info;
	}

	//授权
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//授权信息对象
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//查询相关权限,注入到shiroManager中做全局拦截,拦截方式:manager path拦截和前端jsp shiro annotate拦截(例如:<shiro:hasrole ...>)
		Users userInfo = (Users) arg0.getPrimaryPrincipal();
		String roleID=userInfo.getRoleId();
		List<String> list =userDao.selectPermissionByrole(roleID);
		String role = userDao.selectByID(roleID);
		info.addStringPermissions(list);
		info.addRole(role);
		logger.debug("role,permission,{},{}",role,list);
		return info;
	}

}
